package com.qingzhuge.manager.security.rest;

import com.qingzhuge.common.HttpCode;
import com.qingzhuge.controller.base.AbstractController;
import com.qingzhuge.dto.response.ResponseBodyDto;
import com.qingzhuge.manager.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zeroxiao
 * @date 2019/9/11 10:57
 * 授权、根据token获取用户详细信息
 */
@Api(tags = "S后台登录")
@Slf4j
@RestController
@RequestMapping("/api/sys/open")
public class SysLoginController extends AbstractController {

    @ApiOperation(value = "登录")
    @GetMapping(value = "login")
    public ResponseEntity<ResponseBodyDto<HttpCode>> doLogin() {
        if (null != SecurityUtils.getUserDetails()) {
            return returnSuccess();
        } else {
            return returnSuccess(HttpCode.FORBIDDEN);
        }
    }

    /**
     * 登录授权
     */
    @ApiOperation(value = "登录")
    @PostMapping(value = "login")
    public ResponseEntity<ResponseBodyDto<AuthenticationInfo>> login(@Validated @RequestBody AuthorizationUser authorizationUser){
        log.debug("登录成功:[{}]>>[{}]",getUid(),authorizationUser);
        // 返回 token
        return returnSuccess();
    }

    @ApiOperation(value = "登出")
    @PostMapping(value="logout")
    public ResponseEntity<ResponseBodyDto<String>> logout (HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return returnSuccess();
    }
}
